from flask import Blueprint, render_template, redirect, url_for, flash, request, abort, current_app
from flask_login import login_required, current_user
from app import db
from app.models.question import Question, Tag
from app.models.answer import Answer, Like
from app.forms.question_forms import QuestionForm, AnswerForm, SearchForm
from app.utils import AuthUtil, LogUtil

question = Blueprint('question', __name__)

@question.route('/create', methods=['GET', 'POST'])
@login_required  # 装饰器: 确保用户已登录，未登录则重定向到登录页面
def create():
    form = QuestionForm()
    search_form = SearchForm()
    
    # 获取所有标签供选择
    tags = Tag.query.all()
    form.tags.choices = [(tag.id, tag.name) for tag in tags]
    
    if form.validate_on_submit():
        question = Question(
            title=form.title.data,
            content=form.content.data,
            user_id=current_user.id
        )
        
        # 添加标签
        selected_tags = form.tags.data
        for tag_id in selected_tags:
            tag = Tag.query.get(tag_id)
            if tag:
                question.tags.append(tag)
        
        db.session.add(question)
        db.session.commit()
        flash('问题发布成功', 'success')
        return redirect(url_for('question.detail', id=question.id))
    
    return render_template('question/create.html', form=form, search_form=search_form)

@question.route('/<int:id>', methods=['GET', 'POST'])
def detail(id):
    question = Question.query.get_or_404(id)
    search_form = SearchForm()
    
    # 增加浏览量
    question.view_count += 1
    db.session.commit()
    
    # 回答表单处理
    form = AnswerForm()
    if form.validate_on_submit():
        if not current_user.is_authenticated:
            flash('请先登录再回答问题', 'warning')
            return redirect(url_for('auth.login', next=request.path))
        
        answer = Answer(
            content=form.content.data,
            question_id=question.id,
            user_id=current_user.id
        )
        db.session.add(answer)
        db.session.commit()
        flash('回答提交成功', 'success')
        return redirect(url_for('question.detail', id=question.id))
    
    # 分页获取回答
    page = request.args.get('page', 1, type=int)
    answers = Answer.query.filter_by(question_id=question.id).paginate(
        page=page, per_page=current_app.config['QUESTIONS_PER_PAGE'], error_out=False)
    
    return render_template('question/detail.html', 
                        question=question, 
                        answers=answers, 
                        form=form,
                        search_form=search_form)

@question.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required  # 装饰器: 确保用户已登录，未登录则重定向到登录页面
def edit(id):
    question = Question.query.get_or_404(id)
    search_form = SearchForm()
    
    # 检查权限
    if question.user_id != current_user.id:
        abort(403)
    
    form = QuestionForm()
    
    # 获取所有标签供选择
    tags = Tag.query.all()
    form.tags.choices = [(tag.id, tag.name) for tag in tags]
    
    if form.validate_on_submit():
        question.title = form.title.data
        question.content = form.content.data
        
        # 更新标签
        question.tags = []
        selected_tags = form.tags.data
        for tag_id in selected_tags:
            tag = Tag.query.get(tag_id)
            if tag:
                question.tags.append(tag)
        
        db.session.commit()
        flash('问题更新成功', 'success')
        return redirect(url_for('question.detail', id=question.id))
    
    # 表单预填充
    form.title.data = question.title
    form.content.data = question.content
    form.tags.data = [tag.id for tag in question.tags]
    
    return render_template('question/create.html', form=form, search_form=search_form, question=question)

@question.route('/<int:id>/delete', methods=['POST'])
@login_required  # 装饰器: 确保用户已登录，未登录则重定向到登录页面
def delete(id):
    question = Question.query.get_or_404(id)
    
    # 使用AuthUtil工具类进行权限检查
    if question.user_id != current_user.id:
        LogUtil.warning(f"用户 {current_user.id} 尝试删除不属于他的问题 {id}")
        abort(403)
    
    db.session.delete(question)
    db.session.commit()
    LogUtil.info(f"问题 {id} 已被用户 {current_user.id} 删除")
    flash('问题已删除', 'success')
    return redirect(url_for('main.index'))

@question.route('/answer/<int:id>/like', methods=['POST'])
@login_required  # 装饰器: 确保用户已登录，未登录则重定向到登录页面
def like_answer(id):
    answer = Answer.query.get_or_404(id)
    
    # 检查是否已点赞
    existing_like = Like.query.filter_by(user_id=current_user.id, answer_id=answer.id).first()
    
    if existing_like:
        # 取消点赞
        db.session.delete(existing_like)
        db.session.commit()
        return redirect(url_for('question.detail', id=answer.question_id))
    
    # 添加点赞
    like = Like(user_id=current_user.id, answer_id=answer.id)
    db.session.add(like)
    db.session.commit()
    
    return redirect(url_for('question.detail', id=answer.question_id)) 